Component({
  properties: {
    md: {
      type: String,
      value: '',
      observer: function(newVal) {
        if (newVal) {
          this.parseMd(newVal);
        }
      }
    }
  },

  data: {
    article: {}
  },

  methods: {
    parseMd(md) {
      try {
        console.log('解析markdown内容:', md);
        const app = getApp();
        const article = app.towxml(md, 'markdown', {
          theme: 'dark',
          events: {
            tap: (e) => {
              // 处理代码复制
              if (e.currentTarget.dataset.data && e.currentTarget.dataset.data.text) {
                wx.setClipboardData({
                  data: e.currentTarget.dataset.data.text,
                  success: () => {
                    wx.showToast({
                      title: '代码已复制',
                      icon: 'success'
                    });
                  }
                });
              }
            },
            // 处理图片点击
            imgtap: (e) => {
              const node = e.currentTarget.dataset.data;
              if (node.attr && node.attr.src) {
                wx.previewImage({
                  current: node.attr.src,
                  urls: [node.attr.src]
                });
              }
            }
          }
        });
        console.log('解析结果:', article);
        this.setData({ article });
      } catch (error) {
        console.error('Markdown解析错误:', error);
        const app = getApp();
        const article = app.towxml('内容解析失败', 'markdown', {
          theme: 'dark'
        });
        this.setData({ article });
      }
    }
  }
});
